#!/bin/bash
#
# This script will either enable, or disable, the updating 
#  of openshift rpms via yum
#
##############
# VARIABLES
##############
CONF_FILE="@@CONF_FILE-VARIABLE@@"
PACKAGE_LIST="@@PACKAGE_LIST-VARIABLE@@"

##############
# HELP
##############
function usage() {
  {
  echo "Usage: ${0} <exclude | unexclude>"
  echo
  echo "exclude | disable"
  echo "  exclude packages via an exclude= line in ${CONF_FILE}"
  echo "  This disables updates for ${PACKAGE_LIST} packages"
  echo
  echo "unexclude | enable"
  echo "  removes ${PACKAGE_LIST} from the exclude= line in ${CONF_FILE}"
  echo "  This re-enables updates for packages"
  echo
  echo "status"
  echo "  returns status either 'exclude' or 'unexclude' and 0 or 1 respectively"
  } 1>&2
  exit 1
}

##############
# FUNCTIONS
##############
function exclude_packages() {
  # Ensure there is an exclude line
  if ! grep -q exclude= "${CONF_FILE}" ; then
    echo "Adding exclude= to ${CONF_FILE}"
    sed -i 's|\(installonly_limit=.*\)|\1\nexclude=|' "${CONF_FILE}"
  fi
  # Add each package to the exclude line
  for package in ${PACKAGE_LIST} ; do
    # slashpackage escapes * from variable package
    slashpackage=$(echo ${package} | sed 's|\*|\\\*|g')
    if ! grep exclude= "${CONF_FILE}" | grep -q " ${slashpackage} " ; then
      sed -i "s|exclude=|exclude= ${package} |" "${CONF_FILE}"
    fi
  done
}

function unexclude_packages() {
  # Remove each package to the exclude line
  for package in ${PACKAGE_LIST} ; do
    # slashpackage escapes * from variable package
    slashpackage=$(echo ${package} | sed 's|\*|\\\*|g')
    if grep exclude= "${CONF_FILE}" | grep -q " ${slashpackage} " ; then
      sed -i "s| ${slashpackage} ||" "${CONF_FILE}"
    fi
  done
}

function status() {
  for package in ${PACKAGE_LIST} ; do
    # slashpackage escapes * from variable package
    slashpackage=$(echo ${package} | sed 's|\*|\\\*|g')
    if ! grep exclude= "${CONF_FILE}" | grep -q " ${slashpackage} " ; then
      >&2 echo "unexclude -- At least one package not excluded" 
      return 1
    fi
  done
  >&2 echo "exclude -- All packages excluded"
  return 0
}

##############
# MAIN PROGRAM
##############
case "$1" in
  exclude | disable )
    exclude_packages
    ;;
  unexclude | enable )
    unexclude_packages
    ;;
  status )
    exit $(status)
    ;;
  * )
    echo "Unknown Option: ${1}"
    echo
    usage
    ;;
esac

exit 0
